import {
	baseURL
} from './config.js'
export const request = (opts) => {
	let data = opts.data || {}
	const query = opts.query || false
	let url = baseURL + opts.url
	let params = {
		// 'token': uni.getStorageSync('Token') || ''
	}
	for (let key in data) {
		params[key] = data[key]
	}
	if (query) {
		let parameter = Object.keys(query).map(key => key + "=" + query[key]).join("&");
		url = `${url}?${parameter}`
	}
	let defaultOpts = {
		header: opts.header ? {
			...opts.header,
			'token': uni.getStorageSync('Token') || ''
		} : {
			'Content-type': 'application/json',
			'token': uni.getStorageSync('Token') || ''
		},
		url,
		method: opts.method || 'GET',
		dataType: opts.dataType || 'json',
		'Access-Control-Allow-Origin': '*',
		data: params
	}
	let promise = new Promise(function(resolve, reject) {
		uni.request(defaultOpts).then((response) => {
				// console.log(response[1]);
				if (response[1].data.code == 1) {
					resolve(response[1].data)
				} else if (response[1].data.code == 401) {
					uni.removeStorageSync('userInfo')
					uni.removeStorageSync('token')
					uni.showToast({
						icon: 'none',
						title: '登录状态已过期，请重新登录',
						duration: 2000
					});
					uni.hideLoading()
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/home/index'
						})
					}, 1000)
				} else {
					uni.hideLoading()
					if (opts.reveal) {
						uni.showToast({
							icon: 'none',
							title: response[1].data.msg,
							duration: 2000
						});
					}
				}
			})
			.catch((error) => {
				reject(error)
				uni.showToast({
					icon: 'none',
					title: '网络错误,请稍后重试!',
					duration: 2000
				});
			})
	})

	return promise
}